package services.mes

import play.api.libs.json.{JsValue, Json}
import play.api.libs.ws.WSClient
import play.api.{Configuration, Logging}
import javax.inject.{Inject, Singleton}
import scala.concurrent.duration.DurationInt
import scala.concurrent.{ExecutionContext, Future}

@Singleton
protected class MoreMesPost @Inject()(
                                       ws: WSClient,
                                       config: Configuration
                                     )(implicit exec: ExecutionContext)
  extends Logging {

  var kdAppConfig = config.get[MoreMesConfig]("") // test

  def setConfig(mesconfig: String) = {
    this.kdAppConfig = config.get[MoreMesConfig](mesconfig)
    this
  }

  private def post(
                    apiUrl: String = "/mc/http/interface.ms",
                    model: String,
                    method: String,
                    body: JsValue,
                    kddc: MoreMesConfig = kdAppConfig
                  ) = {
    //    println(parameters)
    var data: JsValue = body //Json.obj()
    try {
      ws.url(kddc.serverUrl + apiUrl)
        .addQueryStringParameters("model" -> model, "method" -> method)
        .addHttpHeaders("Content-Type" -> "application/json;charset=utf-8;")
        .withRequestTimeout(120.seconds)
        .post(data)
        .map(r => {
          errorString(r.body)
        })
    } catch {
      case io: scala.concurrent.TimeoutException => Future("""{"MSG":"接口超时","RESULT":"FAIL","result": false}""")
      case e: Exception => {
        logger.error("mesapi post error", e)
        Future("""{"MSG":"接口异常","RESULT":"FAIL","result": false}""")
      }
    }
  }

  private def errorString(res: String) = {
    val n1 = res.indexOf("<textarea")
    val n2 = res.indexOf("</textarea")
    if (n1 >= 0 && n2 >= 0) res.substring(n1, n2 + 11)
    else res
  }

  /**
   * 删除MES单据
   *
   * @param doc_no   单据编号
   * @param doc_type 单据类型
   *                 DOC_TYPE 1:工单, 2:工单BOM, 3:入库单, 4:出库单，5:调拨单
   * @return
   */
  def deleteDoc(doc_no: String, doc_type: String) = {
    //model=WmsDelete&method=DeleteDoc
    //    {"DOC_NO": "A202204240001","DOC_TYPE": "1",}
    val docType = doc_type match {
      case "mo" => "1"
      case "ppbom" => "2"
      case "stockin" => "3"
      case "stockout" => "4"
      case "move" => "5"
      case _ => doc_type
    }
    val para = Json.obj("DOC_NO" -> doc_no, "DOC_TYPE" -> docType)
    logger.debug("deleteDoc" + para.toString())
    this.post(model = "WmsDelete", method = "DeleteDoc", body = para)
  }

  def saveMO(data: JsValue) = {
    logger.debug("saveProduct: " + data.toString())
    this.post(model = "productbase", method = "SaveProductbaseInfoHttp", body = data)
  }

  def savePPBom(data: JsValue) = {
    logger.debug("saveProjectBom: " + data.toString())
    this.post(model = "projectbom", method = "SaveProjectBomInfoHttp", body = data)
  }

  def saveItem(data: JsValue) = {
    logger.debug("saveItem: " + data.toString())
    this.post(model = "ItemInfo", method = "SaveItemInfoHttp", body = data)
  }

  def saveBom(data: JsValue) = {
    logger.debug("saveProuductBom: " + data.toString())
    this.post(model = "productbom", method = "SaveProductBomInfoHttp", body = data)
  }

  def saveSupplier(data: JsValue) = {
    logger.debug("saveSupplier: " + data.toString())
    this.post(model = "supplier", method = "SaveSupplierInfohttp", body = data)
  }

  def saveStockIn(data: JsValue) = {
    logger.debug("saveStockIn: " + data.toString())
    // /N2/http/interface.ms?model=StockIn&method=StockInHTTP
    this.post(model = "StockIn", method = "StockInHTTP", body = data)
  }

  def saveStockOut(data: JsValue) = {
    logger.debug("saveStockOut: " + data.toString())
    // /N2/http/interface.ms?model=StockOut&method=StockOutHTTP
    this.post(model = "StockOut", method = "StockOutHTTP", body = data)
  }

  def stockMove(data: JsValue) = {
    logger.debug("stockMove: " + data.toString())
    //  # /N2/http/interface.ms?model=WmsDoc&method=SyncAllotDoc
    //  #/N2/http/interface.ms?model=allotInfo&method=SaveAllotInfo
    this.post(model = "allotInfo", method = "SaveAllotInfo", body = data)
  }

}
